package com.czl.elm.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.czl.elm.config.security.JwtTokenUtil;

import com.czl.elm.dao.UsersLoginMapper;
import com.czl.elm.domain.UsersLoginParam;
import com.czl.elm.service.UsersLoginService;
import com.czl.elm.util.ActionResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

@Service
public class UsersLoginServiceImpl implements UsersLoginService {
    @Autowired
    private UsersLoginMapper usersMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Value("${jwt.tokenHead}")
    private String tokenHead;


    /**
     * 登录操作
     * @param phoneName
     * @param password
     * @param checkCode
     * @param httpServletRequest
     * @return
     */
    @Override
    public ActionResult login(String phoneName, String password, String checkCode,HttpServletRequest httpServletRequest) {
       //登录

        JSONObject jsonObject = new JSONObject();
        UserDetails userDetails=userDetailsService.loadUserByUsername(phoneName);

        //验证验证码
        String captcha = (String) httpServletRequest.getSession().getAttribute("captcha");
        if(captcha==null){
            jsonObject.put("status", 404);
            return ActionResult.error("验证码未生成",jsonObject);
        }
        if (StringUtils.isEmpty(checkCode)|| !captcha.equals(checkCode)){
            jsonObject.put("status", 0);
            return ActionResult.error("验证码填写错误",jsonObject);
        }
        if(null==userDetails){
            jsonObject.put("status", 2);
            return ActionResult.error("无此用户",jsonObject);
        }
        if(userDetails.getPassword()==null){
            jsonObject.put("status", 3);
            return ActionResult.error("用户未设置密码",jsonObject);
        }
//        System.out.println(userDetails.getPassword());
//        System.out.println(passwordEncoder.encode(password));
//        System.out.println(password);
        if(!passwordEncoder.matches(password,userDetails.getPassword())){
            jsonObject.put("status", 4);
            return ActionResult.error("用户密码不正确",jsonObject);
        }
//        if(!(password.equals(userDetails.getPassword()))){
//            jsonObject.put("status", 4);
//            return ActionResult.error("用户密码不正确",jsonObject);
//        }
        if(!userDetails.isEnabled()){
            jsonObject.put("status", 5);
            return ActionResult.error("账户被冻结，请联系管理员",jsonObject);
        }
        //更新security登录对象
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken=new UsernamePasswordAuthenticationToken(
                userDetails,
                null,
                userDetails.getAuthorities()
        );
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);


        //生成token
        String token=jwtTokenUtil.generateToken(userDetails);
        //Map<String,String> tokenMap=new HashMap<>();
        jsonObject.put("token",token);
        jsonObject.put("tokenHead",tokenHead);
        jsonObject.put("status", 1);
        return ActionResult.success("登录成功",jsonObject);
    }

    /**
     * 手机登录
     * @param phoneName
     * @param checkCode
     * @param httpServletRequest
     * @return
     */
    @Override
    public ActionResult loginbyphone(String phoneName, String checkCode, HttpServletRequest httpServletRequest) {
        //登录
        JSONObject jsonObject = new JSONObject();
        //System.out.println(passwordEncoder.encode("123"));

        //验证验证码
        String captcha = "1111";
        if (StringUtils.isEmpty(checkCode)|| !captcha.equals(checkCode)){
            jsonObject.put("status", 0);
            return ActionResult.error("验证码填写错误",jsonObject);
        }
        boolean isNewUser=false;
        if(getUsersByUserName2(phoneName)==null){
            if(createNewUsers(phoneName)){
                isNewUser=true;
            }else{
                jsonObject.put("status", 4);
                return ActionResult.error("新用户登录失败",jsonObject);
            }
        }

        UserDetails userDetails=userDetailsService.loadUserByUsername(phoneName);
        //更新security登录对象
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken=new UsernamePasswordAuthenticationToken(
                userDetails,
                null,
                userDetails.getAuthorities()
        );
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);


        //生成token
        String token=jwtTokenUtil.generateToken(userDetails);
        //Map<String,String> tokenMap=new HashMap<>();
        jsonObject.put("token",token);
        jsonObject.put("tokenHead",tokenHead);
        if(isNewUser) {
            jsonObject.put("status", 2);
            return ActionResult.success("新用户登录成功",jsonObject);
        }else{
            jsonObject.put("status", 1);
            return ActionResult.success("登录成功",jsonObject);
        }

    }


    /**
     * 通过手机号获取登录用户信息
     * @param phoneName
     * @return
     */

    @Override
    public UsersLoginParam getUsersByUserName2(String phoneName) {
        return usersMapper.selectUserByName2(phoneName);
    }


    /**
     * 新建用户
     * @param phoneName
     * @return
     */

    private boolean createNewUsers(String phoneName) {
        String userName="饿了吧用户";
        String profile="/profile/default.jpeg";
        String identity="users";
        return usersMapper.addUser(phoneName,userName,profile,identity,1)>0?true:false;
    }
}
